import { createRouter, createWebHistory } from 'vue-router'
import Login from '../components/Login.vue'
import HomeView from '../views/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
  {
    path: '/login',
    component: Login,
    meta: { requiresGuest: true } // 只允许未登录用户访问
  },
    {
      path: '/',
      name: 'home',
      meta: { requiresAuth: true }, // 需要登录才能访问
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    {
    path: '/:pathMatch(.*)*',
    redirect: '/' // 404 重定向到首页
    }
  ],
})
// 路由守卫：控制是否允许访问
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()

  // 需要登录才能访问的页面
  if (to.meta.requiresAuth && !authStore.user) {
    next('/login')
  }
  // 已登录用户访问登录页，重定向到首页
  else if (to.meta.requiresGuest && authStore.user) {
    next('/')
  }
  else {
    next()
  }
})

// 注意：useAuthStore 需要在 router 创建之后导入，避免循环依赖
import { useAuthStore } from '../stores/authStore'

export default router
